package wxapp

import (
	"github.com/silenceper/wechat/v2"
	"github.com/silenceper/wechat/v2/cache"
	"github.com/silenceper/wechat/v2/miniprogram/auth"
	offConfig "github.com/silenceper/wechat/v2/miniprogram/config"
	"github.com/silenceper/wechat/v2/miniprogram/qrcode"
	"server/global"
)

//微信SDK For Golang
//https://silenceper.com/wechat/

// AuthLogin 小程序授权登录
func AuthLogin(jsCode string) (auth.ResCode2Session, error) {
	memory := cache.NewMemory()
	cfg := &offConfig.Config{
		AppID:     global.GL_CONFIG.WxApp.AppID,
		AppSecret: global.GL_CONFIG.WxApp.AppSecret,
		Token:     "",
		Cache:     memory,
	}
	wc := wechat.NewWechat()
	mini := wc.GetMiniProgram(cfg)
	a := mini.GetAuth()
	session, err := a.Code2Session(jsCode)
	return session, err
}

// GetQrcode 获取小程序码
func GetQrcode(params string) ([]byte, error) {
	memory := cache.NewMemory()
	cfg := &offConfig.Config{
		AppID:     global.GL_CONFIG.WxApp.AppID,
		AppSecret: global.GL_CONFIG.WxApp.AppSecret,
		Token:     "",
		Cache:     memory,
	}
	wc := wechat.NewWechat()

	mini := wc.GetMiniProgram(cfg)
	qr := mini.GetQRCode()
	var CheckPath *bool = new(bool)
	*CheckPath = false
	coderParams := qrcode.QRCoder{
		Page:       "pages/index/index",
		Scene:      params,
		CheckPath:  CheckPath,
		EnvVersion: "trial", //要打开的小程序版本。正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
	}
	unlimit, err := qr.GetWXACodeUnlimit(coderParams)

	return unlimit, err
}
